<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Add a task</title>
</head>
<body>
<?php
/**
 * 这是一个使用预处理语句的示例，建议使用键名占位符
 * User: ford
 * Date: 15-8-11
 * Time: 下午3:13
 */
try {
	$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', 'al8840dd');

	if(($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['task'])) {
		if(isset($_POST['parent_id']) && filter_var($_POST['parent_id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
			$parent_id = $_POST['parent_id'];
		} else {
			$parent_id = 0;
		}

		//添加任务到数据库
		$q = "INSERT INTO tasks(parent_id, task) VALUES(:parent_id, :task)";
		$smdt = $pdo->prepare($q);

		//这里不需要防止注入了
		if($smdt->execute(array(':parent_id' => $parent_id, ':task' => $_POST['task']))) {
			 echo '<p>The task has been added!</p>';
		} else {
			echo '<p>The task could not be added!</p>';
		}
	}
	echo '
		<form action="add_task_prepare.php" method="post">
			<fieldset>
				<legend>Add Task</legend>
				<p>Task: <input type="text" name="task" size="60" maxlength="100"></p>
				<p>Parent Task:
					<select name="parent_id">
						<option value="0">None</option>
	';
	//添加任务表
	$q = 'SELECT task_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00" ORDER BY date_added ASC';
	$r = $pdo->query($q);
	$r->setFetchMode(PDO::FETCH_NUM);

	while($row = $r->fetch()) {
		echo '			<option value="' . $row[0] . '">' . $row[1] . '</option>';
	}

	echo '
					</select>
				</p>
				<input name="submit" type="submit" value="Add This Task">
			</fieldset>
		</form>
	';
	unset($pdo);
} catch(PDOException $e) {
	echo '<p>An error occurred: ' . $e->getMessage() . '</p>';
}
?>
</body>
</html>
